<template>
  <div class="content">
    <NavTop class="navtop-content">
      <BackBtn />
      <div class="navtop-title">{{ groupInfo.groupName }}</div>
      <van-icon name="ellipsis" class="more-icon" @click="popShow=true" v-if="$route.query._id !== userId && userState === 1"/>
    </NavTop>
    <!-- 弹出层 -->
    <van-popup class="pop-content" v-model="popShow" position="bottom" :style="{ height: popHeight }" >
      <div class="update-group" v-if="userId === groupInfo.userId" @click="updateGroup">编辑资料</div>
      <div class="out-group" @click="outGroup">退出群聊</div>
    </van-popup>
    <div class="group-content">
      <div class="group-info-top">
        <div class="group-pic" @click="lookPic($baseUrl + groupInfo.imgUrl)">
          <img :src="$baseUrl + groupInfo.imgUrl" alt="" />
        </div>
        <div class="group-info">
          <div class="group-name">{{ groupInfo.groupName }}</div>
          <div class="group-number">{{ groupInfo.groupNumber }}</div>
        </div>
      </div>
      <div class="group-createTime">
        <van-icon class="time-icon" name="underway-o" />
        <span>创建时间：{{ groupInfo.creatTime }}</span>
      </div>
    </div>
    <!-- 群简介 -->
    <div class="group-sign-content" v-if="groupInfo.sign">
      <div class="content-title">群简介</div>
      <div class="sign-text">{{ groupInfo.sign }}</div>
    </div>
    <!-- 群成员列表 -->
    <div class="group-people-content">
        <div class="content-title">群成员（{{ groupUserList.length }}人）</div>
        <ul>
            <li v-for="(item,index) in groupUserList" :key="index" @click="goUserHome(item.userId._id)">
                <div class="user-pic">
                    <img :src="$baseUrl + item.userId.imgUrl" alt="">
                </div>
                <div class="user-nick">{{ item.userId.nick }}</div>
                <van-tag 
                  color="#ffe1e1"
                  text-color="#ad0000"
                  v-if="item.userId._id === groupInfo.userId"
                >群主</van-tag>
            </li>
        </ul>
    </div>
    <div class="box"></div>
    <div class="bottom">
        <div class="send-btn" @click="handleBtnClick">{{ btnText }}</div>
    </div>
  </div>
</template>

<script>
import BackBtn from "@/components/BackBtn"
import NavTop from "@/components/NavTop"
import { reqGetGroupHome, reqGetGroupUserList, reqAddGroup, reqDelGroupUser, reqDelGroup } from '@/api'
import { ImagePreview, Toast, Dialog } from 'vant'
import { mapState } from "vuex"
export default {
  components: {
    BackBtn,
    NavTop
  },
  data() {
    return {
      groupInfo: {},
      groupUserList: [],
      userState: null,
      popShow: false
    }
  },
  computed: {
    ...mapState({
      userId: state => state.login.userInfo._id
    }),
    // 底部按钮文字
    btnText() {
      // 当前用户群状态（0:申请中，1:已为加入该群，2:未加入群）
      const { userState } = this
      if (userState === 0) {
        return '申请中'
      } else if (userState === 1) {
        return '发消息'  // 已加入该群
      } else if (userState === 2) {
        return '加入群聊'
      }
    },
    popHeight() {
      if (this.userId === this.groupInfo.userId) {
        return '2.9333rem'
      } else {
        return '1.4667rem'
      }
    }
  },
  methods: {
    // 获取群信息
    async getGroupHome() {
      let groupId = this.$route.query._id // 群id
      let userId = this.userId // 当前用户id
      let res = await reqGetGroupHome({groupId, userId})
      if (res.status === 200) {
        this.groupInfo = res.data
        // 当前用户群状态（0:申请中，1:已为加入该群，2:未加入群）
        this.userState = res.state
      }
    },
    // 获取群成员
    async getGroupUserList() {
      let groupId = this.$route.query._id
      let res = await reqGetGroupUserList({groupId})
      if (res.status === 200) {
        this.groupUserList = res.data
      }
    },
    // 查看用户头像
    lookPic(imgUrl) {
      ImagePreview({
          images: [imgUrl],
          loop: false,
          closeable: true
      })
    },
    // 去用户主页
    goUserHome(_id) {
      this.$router.push({
        path: '/userhome',
        query: {
          _id
        }
      })
    },
    // 底部按钮
    async handleBtnClick() {
      /**
       * userState => 0  申请中
       * userState => 1  发消息
       * userState => 2  加好友
       */
      const { userState } = this
      let groupId = this.$route.query._id
      if (userState === 0) {
        // 申请中，不能点击
        return
      } else if (userState === 1) {
        // 发消息
        this.$router.push({
          path: '/messagedetails/groupChat',
          query: {
            _id: groupId
          }
        })
      } else if (userState === 2) {
        // 发送申请
        let ids = {
          groupId,
          userId: this.userId
        }
        let res = await reqAddGroup(ids)
        if (res.status === 200) {
          this.userState = 0
          // 触发socket
          this.$socket.emit('apply_notice', this.groupInfo.userId) // 群主id
        }
        Toast(res.msg)
      }
    },
    // 退出群聊
    outGroup() {
      Dialog.confirm({
        title: '温馨提示',
        message: '确定要退出该群聊吗？'
      }).then(async () => {
        // 确认
        // 退出群聊分为群主和群成员（群主退群是将群直接解散，群成员只是将群成员删除）
        let groupLeaderId = this.groupInfo.userId  // 群主id
        let userId = this.userId  // 当前用户id
        let groupId = this.groupInfo._id  // 群id
        if (groupLeaderId === userId) {
          // 群主
          let res = await reqDelGroup({groupId})
          if (res.status === 200) {
            Toast('群已解散')
            this.$router.push('/message')
          } else {
            Toast('解散失败')
          }
        } else {
          // 群成员
          let ids = { groupId, userId }
          let res = await reqDelGroupUser(ids)
          if (res.status === 200) {
            Toast('退群成功')
            this.$router.push('/message')
          } else {
            Toast('退群失败')
          }
        }
      })
      .catch(() => {
        // 取消
        this.popShow = false
      })
    },
    // 修改群信息
    updateGroup() {
      this.$router.push({
        path: '/creategroup/编辑群聊',
        query: {
          _id: this.$route.query._id,
          leaderId: this.groupInfo.userId
        }
      })
    }
  },
  mounted() {
    this.getGroupHome()
    this.getGroupUserList()
  }
}
</script>

<style lang="less" scoped>
.navtop-content {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
}
.content {
  width: 100%;
  height: 100vh;
  padding-top: 1.3333rem;
  box-sizing: border-box;
  background-color: #f6f6f6;
}
.pop-content {
  display: flex;
  flex-direction: column;
  .update-group, .out-group {
    width: 100%;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 0.4rem;
  }
  .update-group {
    border-bottom: 0.04rem solid #eae8e8;
  }
  .out-group {
    color: #f06262;
  }
}
.more-icon {
  position: fixed;
  top: 0.4rem;
  right: 0.4rem;
  font-size: 0.5333rem;
  color: #fff;
  font-weight: 700;
}
.group-content {
  width: 100%;
  background-color: #fff;
  padding: 0.1333rem 0.4rem 0.3333rem;
  box-sizing: border-box;
  margin-bottom: .3333rem;
  .group-info-top {
    width: 100%;
    height: 1.4667rem;
    display: flex;
    align-items: center;
    margin-bottom: .4rem;
    .group-pic {
      width: 1.4667rem;
      height: 1.4667rem;
      border-radius: 50%;
      overflow: hidden;
      margin-right: .4rem;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .group-info {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        .group-name {
            font-size: .4667rem;
            margin-bottom: .2667rem;
        }
    }
  }
  .group-createTime {
    font-size: .3333rem;
    color: #858585;
    .time-icon {
        font-weight: 700;
    }
    span {
        margin-left: .1333rem;
    }
  }
}
.group-sign-content {
  width: 100%;
  background-color: #fff;
  padding: .4667rem .4rem;
  box-sizing: border-box;
  margin-bottom: 0.3333rem;
  .content-title {
    font-size: .4rem;
    margin-bottom: .4rem;
  }
  .sign-text {
    font-size: .3733rem;
    line-height: .5333rem;
  }
}
.group-people-content {
    width: 100%;
    background-color: #fff;
    padding: .4667rem .4rem .2667rem;
    box-sizing: border-box;
    .content-title {
        font-size: .4rem;
        margin-bottom: .4rem;
    }
    ul {
        li {
            width: 100%;
            height: 1.4667rem;
            display: flex;
            align-items: center;
            .user-pic {
                width: 1.0667rem;
                height: 1.0667rem;
                overflow: hidden;
                border-radius: 50%;
                img {
                    width: 100%;
                    height: 100%;
                }
            }
            .user-nick {
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                font-size: .4rem;
                margin-left: .2667rem;
            }
        }
    }
}
.box {
  width: 100%;
  height: 1.6667rem;
}
.bottom {
    width: 100%;
    height: 1.6667rem;
    background-color: #fff;
    border-top: 0.04rem solid #dbdada;
    padding: .2667rem .4rem;
    box-sizing: border-box;
    position: fixed;
    left: 0;
    bottom: 0;
    .send-btn {
        width: 100%;
        height: 100%;
        background-color: #3c98ff;
        border-radius: .1333rem;
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 0.4rem;
    }
}
</style>

<style>
.van-overlay {
  background-color: rgba(0,0,0,.3);
}
</style>